package com.xhorse.lockplatform.comm.service;

import com.xhorse.lockplatform.comm.enums.ResultEnum;
import com.xhorse.lockplatform.comm.exception.LockPlatFormException;
import com.xhorse.lockplatform.comm.model.BaseId;
import com.xhorse.lockplatform.comm.persist.BaseMapper;
import com.xhorse.lockplatform.comm.util.*;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 数据操作服务基础类
 * @author Think
 */
@Service
public abstract class BaseService<T extends BaseId> {

    protected BaseMapper<T> mapper;

    public T get(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    public int saveOrUpdate(T t) {
        if (t.getId() == null || t.getId() < 1) {
            return save(t);
        } else {
            return update(t);
        }
    }

    public int save(T t) {
        return mapper.insert(t);
    }

    public int update(T t) {
        return mapper.updateByPrimaryKeySelective(t);
    }

    public List<T> listAll() {
        return mapper.selectAll();
    }

    public List<T> list(Paginator page) {
        List<T> list = mapper.select(page);
        return listCom(page,list);
    }

    private List<T> listCom(Paginator page,List<T> list){
        list = initPaginator(page, list);
        if (page.isNeedTotal()) {
            if (page.getPage() > 1 || page.isHasNextPage()) {
                int total = mapper.count(page);
                page.setTotal(total);
            } else if (list != null) {
                page.setTotal(list.size());
            }
        }
        return list;
    }

    public List<T> listByOther(Paginator page,List<T> list) {
        return listCom(page,list);
    }

    protected <K> List<K> initPaginator(Paginator page, List<K> list) {
        if (list == null || list.isEmpty()) {
            page.setHasNextPage(false);
            page.setHasData(false);
            return list;
        } else {
            page.setHasData(true);
            if (!page.isPageless() && list.size() > page.getSize()) {
                page.setHasNextPage(true);
                return list.subList(0, list.size() - 1);
            } else {
                page.setHasNextPage(false);
                return list;
            }
        }
    }

    public int delete(Integer id) {
        return mapper.deleteById(id);
    }

    public int delete(int[] ids) {
        return mapper.deleteByIds(ids);
    }

    public int insertByBatch(List<T> list) {
        return mapper.insertByBatch(list);
    }

    /**
     * 公共请求方法
     *
     * @param url
     * @param requestBody
     * @param token
     * @return
     */
    public String sendMsg(String url, RequestBody requestBody, String token) {
        HttpClientUtil httpClientUtil = HttpClientUtil.getInstance();
        Request request;
        if (StringUtil.isNotNil(token)) {
            request = new Request.Builder()
                    .url(url)
                    .addHeader("verToken", token)
                    .post(requestBody).build();
        } else {
            request = new Request.Builder()
                    .url(url)
                    .post(requestBody).build();
        }
        try {
            Response response = httpClientUtil.getClient().newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "用户接口[" + url + "]，遇到异常", e);
        }
    }

    public String encryptToken(String username) {
        byte[] byteArray = DecriptUtil.encryptAES(username, "4c6971d6df46e89f");
        String prefix = ByteTransferUtil.bytesToHexString(byteArray);
        String suffix = DecriptUtil.MD5(username + "aMhFJ6");
        return suffix + prefix;
    }
}
